<template>
    <div>
      <TopBar ref="topBar" :tabName="tabName" :backValue="backValue">
        <template #operate>
          <el-button @click="prevHandle()" v-if="activeStep >= 1" :loading="loading">上一步</el-button>

          <el-button type="primary" style="min-width: 68px" @click="nextHandle()" :loading="loading">
              <span v-if="activeStep == 0">下一步</span>
              <span v-if="activeStep >= 1">保存</span>
          </el-button>
        </template>
      </TopBar>
      <div class="page-main" v-loading="loading">
        <div class="stepBar-box">
          <div v-for="(item, index) in stepBarList" :key="item" 
            :class="`stepBar-item ${activeStep === index ? 'stepBar-activeItem' : ''}`">{{ item }}</div>
        </div>
        <el-form class="myForm" v-show="activeStep === 0" ref="formRef" :model="form" label-width="auto">
          <el-form-item label="活动名称" prop="activeName" :rules="getRules('input', '活动名称')">
            <el-input style="width: 360px;" v-model="form.activeName" placeholder="请输入" show-word-limit
              :maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="活动时间">
            <div>
              <el-radio-group v-model="form.activeDateType" @change="activeDateTypeChange" :disabled="disabled">
                <el-radio :label="0">指定周期</el-radio>
                <el-radio :label="1">指定日期</el-radio>
              </el-radio-group>
              <div v-if="form.activeDateType == 0" style="margin-top: 8px;" class="flex align-items-center">
                <!-- <span style="margin-right: 8px;">每周</span> -->
                <!-- 周月选项卡 -->
                <el-select v-model="form.activityCycleType" @change="activityCycleTypeChange" style="width: 80px;margin-right: 8px;" placeholder="Select" >
                    <el-option
                      v-for="item in chooseWeekOrMonth"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <el-form-item label="" prop="activeDate" :rules="activeDateRule" style="margin-bottom: 0;">
                    <el-select v-model="form.activeDate" 
                    multiple 
                    clearable 
                    collapse-tags-tooltip  
                    collapse-tags
                    :max-collapse-tags="2"
                      placeholder="请选择" style="width: 260px;">
                      <el-option v-for="item in cycleList" :key="item.value" :label="item.label" :value="item.label" />
                    </el-select>
                  </el-form-item>
              
              </div>
              <div v-else style="margin-top: 8px;">
                <el-form-item label="" prop="activeDate" :rules="activeDateRule" style="margin-bottom: 0;">
                    <!-- <el-date-picker 
                    :disabled="disabled"
                    v-model="form.activeDate" 
                    type="datetimerange"
                    @visibleChange="visibleChange"
                    range-separator="~"
                    start-placeholder="请选择开始时间" 
                    end-placeholder="请选择结束时间" 
                    value-format="YYYY-MM-DD HH:mm:ss"
                    popper-class='myDatePicker' 
                    :disabled-date="disabledDate"
                    /> -->
                    <el-date-picker
                    v-model="form.activeDate[0]"
                    type="datetime"
                    :disabled-date="disabledDate"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                    :disabled="timeFirstDisable"
                  />&nbsp;- &nbsp;  
                  <el-date-picker
                    v-model="form.activeDate[1]"
                    type="datetime"
                    :disabled-date="disabledDate"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                  />
                </el-form-item>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="是否限购" prop="isRestriction" :rules="getRules('required', '是否限购')">
            <el-radio-group v-model="form.isRestriction" @change="changeRestriction">
                <el-radio :label="0">关闭限购</el-radio>
                <el-radio :label="1">开启限购</el-radio>
              </el-radio-group>
          </el-form-item>

          <el-form-item style="margin-bottom: 1px;" label="活动对象" prop="activeObject" :rules="getRules('required', '活动对象')">
            <el-radio-group v-model="form.activeObject" @change="changeActiveObject">
                <el-radio :label="0">全部会员</el-radio>
                <el-radio :label="1">指定会员等级</el-radio>
              </el-radio-group>
          </el-form-item>


          <el-form-item label="&nbsp" style="margin-bottom: 1px;" v-if="form.activeObject == 0">
            <el-switch
                v-model="form.memberType"
                active-text="未消费会员"
                inactive-text="全部"
                active-color="#3480FF"
                inactive-color="#3480FF"     
              />
          </el-form-item>
          <div  v-if="form.activeObject == 0" class="member-tips">全部：全部注册会员；未消费会员：注册后消费订单数量为0的会员；</div>
          <el-form-item style="margin-left: 120px;" label="" prop="membershipLevel" :rules="getRules('select', '会员等级')" v-if="form.activeObject == 1">
            <el-select
                v-model="form.membershipLevel"
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="指定会员等级"
                style="width: 260px"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
          </el-select>
          </el-form-item>
         
      
          <el-form-item label="适用门店及业务" prop="useStore" :rules="getRules('select', '适用门店及业务')">
            <div>
              <el-radio-group :model-value="form.useStore" @change="useStoreChange">
                <el-radio :label="0">全部门店及业务</el-radio>
                <el-radio :label="1">指定门店及业务</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item v-if="form.useStore === 1" label="选择门店" prop="storeList" :rules="storeListRule">
            <div style="width: 500px;">
              <el-button style="margin-bottom: 8px;" type="primary" plain @click="handleOpenStoreDialog">
                <el-image :src="btnAddBlue" class="btnIcon" />
                选择门店
              </el-button>
              <el-table :header-cell-style="{ background: '#ddd' }" stripe :data="listData" max-height="300"
                style="width: 100%;">
                <el-table-column show-overflow-tooltip prop="storeName" label="门店名称"></el-table-column>
                <!-- <el-table-column label="理疗馆">
                  <template v-slot="{ row }">
                    {{ row.isHall ? '√' : '' }}
                  </template>
                </el-table-column>
                <el-table-column label="商城">
                  <template v-slot="{ row }">
                    {{ row.isShop ? '√' : '' }}
                  </template>
                </el-table-column> -->
                <el-table-column label="操作">
                  <template v-slot="{ row, $index }">
                    <el-button type="danger" plain @click="delStore(row, $index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="myPagination">
                <el-pagination background v-model:current-page="pageConfig.page" v-model:page-size="pageConfig.pageSize"
                  :page-sizes="pageConfig.pageSizes" :layout="pageConfig.layout" :total="total"
                  @size-change="handleSizeChange" @current-change="CurrentChange" />
              </div>
            </div>
          </el-form-item>
        </el-form>
        <el-form class="myForm" v-show="activeStep === 1" ref="formRef1" :model="form" >
          <el-form-item label="活动范围" prop="rangeActive" :rules="getRules('required', '活动范围')">
            <el-radio-group v-model="form.rangeActive" @change="changeRangeActive">
                <el-radio :label="0"  v-if="form.isRestriction == 0">全部商品可用</el-radio>
                <el-radio :label="1">指定商品可用</el-radio>
                <el-radio :label="2"  v-if="form.isRestriction == 0">指定商品不可用</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label-width="180px" label="可用商品折扣" prop="availablGoods" :rules="discountRules" v-if="form.rangeActive == 2">
            <el-input 
            type="Number" 
            style="width: 100px;" 
            v-model="form.availablGoods"
            placeholder="请输入"
            @input="(val) => handleInput(val,'availablGoods')"
            @blur="handleBlur"
             ></el-input>%
          </el-form-item>
          <el-form-item style="margin-left: 78px;" label="折扣" prop="discount" :rules="discountRules" v-if="form.rangeActive == 0">
            <el-input 
            type="Number" 
            style="width: 100px;margin-right: 8px;" 
            v-model="form.discount"
            placeholder="请输入"
            @input="(val) => handleInput(val,'discount')"
            @blur="handleBlur"
             ></el-input>%
          </el-form-item>
          <el-form-item label="&nbsp" style="margin-bottom: 1px; margin-left: 62px;" v-if="form.rangeActive == 1">
            <el-switch
                v-model="form.chooseRadius"
                active-text="百分比折扣"
                inactive-text="固定价格"
                active-color="#3480FF"
                inactive-color="#3480FF"     
              />
          </el-form-item>
       
          <div class="choose-view" v-if="form.rangeActive != 0">
              <div class="choose-button">
                    <el-button plain type="primary" @click="handleOpenRangeDialog">
                        <img src="@/assets/icon/btn-add-blue.png" alt="" style="margin-right:8px;width:14px;height:14px">
                        选择商品
                    </el-button>
                    <el-button plain type="success" @click="importGoodsHandle">
                        <img src="@/assets/images/green-import.png" alt="" style="margin-right:8px;width:14px;height:14px">
                        导入商品
                    </el-button>
                    <div class="button-tips">单个活动商品同一时间段只能参加一个折扣限购活动</div>
              </div>
              <template v-if="[...Object.values(activeGoods)].flat().length > 0">
              <div class="active-type">
                <el-radio-group v-model="activeType">
                  <el-radio-button label="疗程" />
                  <el-radio-button label="套餐" />
                  <el-radio-button label="项目" />
                  <el-radio-button label="产品" />
                </el-radio-group>
                <div class="button-right">
                  <el-button type="primary" plain @click="bulkFill">批量填充</el-button>
                </div>
              </div>
              <el-table :header-cell-style="{ background: '#ddd' }" stripe max-height="600" :data="goodsListData">
                <el-table-column prop="productName" min-width="300" :label="activeType+'名称'">
                  <template v-slot="{row}">
                    {{ row.comboName || row.projectName ||  row.productName || row.courseName}}
                  </template>
                </el-table-column>
                <el-table-column prop="discountAll" label="折扣(%)" min-width="260" v-if="form.chooseRadius && form.rangeActive == 1">
                  <template #header>
                    <el-input 
                    style="width:132px"
                    v-model="activeGoods[activeType].discountAll" 
                    @input="()=>{activeGoods[activeType].discountAll=limitInt(activeGoods[activeType].discountAll,2)}" 
                    @blur="() => {activeGoods[activeType].discountAll = giveIntMin(activeGoods[activeType].discountAll)}"
                    placeholder="折扣(%)"></el-input>
                  </template>

                  <template v-slot="{row,$index}">
                    <el-form-item label=" " prop="discount" :rules="discountValidateTable(row)">
                      <el-input 
                      style="width: 120px;"
                      v-model="row.discount" 
                      @input="()=>{row.discount=limitInt(row.discount,2)}" 
                      @blur="() => {row.discount = giveIntMin(row.discount)}"
                      placeholder="折扣(%)"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="discountPrice" label="折后价(元)" min-width="260" v-if="!form.chooseRadius">
                  <template #header>
                    <el-input 
                    style="width:132px"
                    v-model="activeGoods[activeType].discountPriceAll"  
                    @input="()=>{activeGoods[activeType].discountPriceAll=limitFloat(activeGoods[activeType].discountPriceAll)}" 
                    @blur="() => {activeGoods[activeType].discountPriceAll = giveFloatMin(activeGoods[activeType].discountPriceAll)}"
                    placeholder="折后价(元)"></el-input>
                  </template>
                  <template v-slot="{row,$index}">
                    <el-form-item label=" " prop="discountPrice" :rules="discountPrice(row)">
                      <el-input 
                      style="width: 120px;" 
                      v-model="row.discountPrice" 
                      @input="()=>{row.discountPrice=limitFloat(row.discountPrice)}" 
                      @blur="() => {row.discountPrice = giveFloatMin(row.discountPrice)}"
                      placeholder="折后价(元)"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column v-if="form.isRestriction == 1" prop="cumulatePriceAll" label="累计限购" min-width="260">
                  <template #header>
                    <el-input 
                    style="width:132px"
                    v-model="activeGoods[activeType].cumulatePriceAll"  
                    @input="()=>{activeGoods[activeType].cumulatePriceAll=limitInt(activeGoods[activeType].cumulatePriceAll,2)}" 
                    @blur="() => {activeGoods[activeType].cumulatePriceAll = giveIntMin(activeGoods[activeType].cumulatePriceAll)}"
                    placeholder="累计限购"></el-input>
                  </template>
                  <template v-slot="{row,$index}">
                    <el-form-item label=" " prop="cumulatePrice" :rules="cumulatePriceRules(row)">
                      <el-input 
                      style="width: 120px;"
                      v-model="row.cumulatePrice"
                      @input="()=>{row.cumulatePrice=limitFloat(row.cumulatePrice,2)}" 
                      @blur="() => {row.cumulatePrice = giveFloatMin(row.cumulatePrice)}"
                      placeholder="累计限购"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" min-width="136">
                  <template v-slot="{row,$index}">
                    <el-button type="danger" plain @click="delActiveGoods($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="page-bar">
                <el-pagination
                  background 
                  v-model:current-page="goodsPageConfig.page" 
                  v-model:page-size="goodsPageConfig.pageSize"
                  :page-sizes="goodsPageConfig.pageSizes" 
                  :layout="goodsPageConfig.layout" 
                  :total="goodsTotal" 
                  @size-change="goodsHandleSizeChange" 
                  @current-change="goodsHandleCurrentChange" 
               />
              </div>
             
            </template>
           
          </div>
         
        </el-form>
      </div>
      <SelectStote ref="selectStoteRef" @backStoreValue="backStoreValue" ></SelectStote>
      <SelectRange ref="selectRangeRef" :groupTypeList="Object.keys(activeGoods)" @backRangeValue="backRangeValue"></SelectRange>
      <ImportMember 
        ref="importMemberRef"
       @backImportRangeValue="backImportRangeValue" 
       :importUrl="importUrl"
       :importData="importData"
       ></ImportMember>
    </div>
  </template>



  <script setup>
  import { useDiffStoreValue, useDiffBrandId} from '../NewcomerDiscount/action'
  import { useTableRefresh, useManualPaging, useImportImg,elementPosition } from '@/hooks/index'
  import { DiscountData } from './index.js';
  import getRules from '@/validUtils';
  import SelectStote from '@/views/OperateManagement/MarketingManagements/CouponOrganize/Components/SelectStote.vue'
  import SelectRange from '@/views/OperateManagement/MarketingManagements/CouponOrganize/Components/SelectRange.vue'
  import ImportMember from './Components/ImportGoods.vue';
  import TopBar from '@/components/Topbar/index.vue';
  import { limitFloat,limitInt,giveFloatMin,giveIntMin } from '@/utils/common.js'
  import { categorizeItems,compareTimestampsAndValidate } from './Hooks/index.js'
  import { activityTypeEnum } from '@/views/OperateManagement/dict.js'
  import { getMemberLevelList } from '@/api/Member/index.js' 
  import { newUserActivityOperate,getNewUserActivityDetail } from '@/api/OperationManage/marketingManagements'
  const btnAddBlue = useImportImg('btn-add-blue')
  
  const route = useRoute()
  const topBar = ref(null)
  const isEdit = computed(() => route.query.id ? true : false)
  const isCopy = computed(() => route.query.isCopy? true : false)
  const isCopyId = computed(() => route.query.isCopyId)
  // const backValue = ref('/operateManagement/marketingManagements/shopActivityIndex')
  // const arr = ['/operateManagement/marketingManagements/myActivityIndex','/operateManagement/marketingManagements/shopActivityIndex']
  const tabName = computed(() => {
  return isCopy.value ? '复制活动' : isEdit.value ? '编辑活动' : '新建活动'
})

const backValue = ref('/operateManagement/marketingManagements/shopActivityIndex')
const arr = ['/operateManagement/marketingManagements/myActivityIndex','/operateManagement/marketingManagements/shopActivityIndex']
const beforeRouteEnter = (path)=>{
  backValue.value = arr.includes(path) ? path :'/operateManagement/marketingManagements/shopActivityIndex'
}
defineExpose({
  beforeRouteEnter
})
  const loading = ref(false)
  const pageId = ref(null)
  const { searchTableRef, weekDateList } = DiscountData()
  
  // onActivated(() => {
  //   if (route.query.id !== pageId.value) {
  //     pageId.value = route.query.id
  //   }
  // })
  
  const activeStep = ref(0)
  const stepBarList = ['基本信息', '活动规则']
  // const stepChange = (index) => {
  //   activeStep.value = index
  // }
  const formRef = ref(null)
  const formRef1 = ref(null)
  const form = ref({
    activeName: '',
    activeDateType: 0,
    activeDate: [],
    // useStore: 1,
    isRestriction:0, //是否限购
    activeObject:0, //活动对象
    memberType:false, //会员类型
    membershipLevel:[], //会员等级
    rangeActive:0, //活动范围
    discount:'', //折扣
    availablGoods:'', //可用商品折扣
    activityCycleType:0,
    chooseRadius:true,//百分比或折后
    useStore:0, // 全部门店或指定
  })

  const disabled = ref(false)

  // 门店列表
  const storeList = ref([])

  // 门店列表选择对比参数
const oldUseStore = ref(1);
const storeType = ref(1);

const timeFirstDisable = ref(false)
/**
 * ===========会员等级参数===========
 */
const options = ref([])

const getMembershipLevel = async() => {
   const res = await getMemberLevelList()
   options.value = res.map(item => {
      return{
        value:item.id,
        label:item.levelName
      }
   })
   console.log(options.value,'options.value');
}
getMembershipLevel()
/**
 * ===========会员等级参数========
 */


// ============回显业务逻辑start===========

onActivated(() => {
  // 处理编辑页面的逻辑
  if (route.query.id && route.query.id !== pageId.value) {
    console.log('执行了');
   
    reset()
    pageId.value = route.query.id
    getDetail(1)
    disabled.value = true
  }else{
    if(isCopy.value && route.query.isCopyId !== pageId.value){
      pageId.value = route.query.isCopyId
      getDetail(2)
    }
  }
})
const getDetail = async (type) => {
  try{
    loading.value = true
    let data = {
      activityId: pageId.value,
      activityType:'2'
    }
    const res = await getNewUserActivityDetail(data)
    // console.log(res,'res');
    // return
    form.value.activeName = res.activityName
    form.value.activeDateType = res.activityTimeType
    form.value.activityCycleType = res.timeCycleType
    form.value.isRestriction = res.isLimited ? 1 : 0
    form.value.activeObject = res.activityMember
    form.value.rangeActive =   res.activityRule
    form.value.chooseRadius = res.discountsType ? true : false
    if(res.activityTimeType){
      form.value.activeDate = [res.activityStartTime,res.activityEndTime]
    }else{

      form.value.activeDate = res?.timeCycleTypeData?.map(item=>cycleList.value[item - 1].label) ?? []
      console.log( res?.timeCycleTypeData,'res?.timeCycleTypeData');
      console.log(cycleList.value,'cycleList.value');
    }
    if(res.activityMember == 0){
      // 全部会员
      form.value.memberType = res.activityMemberType ? true : false
    
    }else{
      // 指定会员
      form.value.membershipLevel = res.memberLevelIdSet 
    }
    form.value.useStore = res.businessScope
    // 反显门店
    storeList.value = res.activityStoreData.map(item=>{
      return{
        id:item.storeId,
        storeName:item.storeName,
        isHall:item?.businessType.includes(1) ?? false,
        isShop:item?.businessType.includes(2)?? false,
        isStore: (item?.businessType.includes(1) || item?.businessType.includes(2)) ?? false,
        hallId:'hall'+item.storeId,
        shopId:'shop'+item.storeId,
        storeId: 'store' + item.storeId,
        brandId:item.brandId || ''
      }
    })
    // 反显活动商品
    if(res.activityRule != 0){
      Object.keys(activeGoods.value).forEach(key=>{
      activeGoods.value[key] = res.activityRuleData.find(item=>item.activityType === activityTypeEnum[key]).ruleData.map(item=>{
        return {
          id:item.productId,
          productName:item.productName,
          discount: res.activityRule == 1 ? res.discountsType ? item.discountedPrices : '' : '',
          discountPrice: res.activityRule == 1 ? res.discountsType == 0 ? item.discountedPrices : '' : '',
          cumulatePrice:item.limitCount || '',
        }
      })
    })
    }
   
    switch (res.activityRule) {
          case 0:
           form.value.discount = res.discounts
            break;
          // case 1:
          //   params.discounts = ''
          //   break;
          case 2:
            form.value.availablGoods = res.discounts
            break;  
          default:
            break;
        }
    if(form.value.activeDateType == 1 && type == 1){
          timeFirstDisable.value = true
        
        }
  }finally{
    loading.value = false
  }
}
// ============回显业务逻辑end===========



// 时间选项卡

const chooseWeekOrMonth = [
          {
              value:0,
              label:"每周"
          },
          {
              value:1,
              label:"每月"
          },
]

const cycleList = computed(() => {
        if(form.value.activityCycleType == 0){
            let cycleList = [];
            for(let i = 1;i<=7;i++){
                let weetText = ["","一","二","三","四","五","六","日"];
                cycleList.push({
                    value:Number(i),
                    label:'周'+weetText[i]
                })
            }
            return cycleList;
        }else if(form.value.activityCycleType == 1){
            let cycleList = [];
            for(let i = 1;i<=31;i++){
                cycleList.push({
                    value:Number(i),
                    label:i+'日'
                })
            }
            return cycleList;
        }
})


const handleInput = (val,valueName) => {
  // console.log(val,valueName,'val');
    form.value[valueName] =  form.value[valueName].replace(/[^\d]/g, ''); // 过滤非数字字符
    const num = parseInt(form.value[valueName], 10); // 转为整数，如果转换失败，默认为1
    form.value[valueName] = Math.min(Math.max(num, ''), 99); // 限制在1到99之间
  }

// ================== 导入模板star ================
const importUrl = ref('https://health-img.91medicine.cn/excel/%E6%8A%98%E6%89%A3%E9%99%90%E8%B4%AD%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx')
// 导入额外参数
const importData = ref({})
// 导入的回调函数
const backImportRangeValue = (rangList) => {
  activeGoods.value = {
    '疗程':[],
    '套餐':[],
    '项目':[],
    '产品':[]
  }
  categorizeItems(rangList,activeGoods.value)
}

  // 导入商品逻辑
  const importMemberRef = ref(null)

  const importGoodsHandle = ()=>{

    importData.value = {
      activityType:2, //导入类型 2:折扣限购
      discountsType: form.value.chooseRadius ? 1 : 0, //优惠类型 0:固定价格 1:百分比折扣
      activityRule: form.value.rangeActive, //0:全部商品可用 1:指定商品可用 2:指定商品不可用
      isLimited:form.value.isRestriction ? 1 : 0, //是否限购 1:是 0:否
      brandIds: storeList.value.map(item => item.brandId).filter(item => item).join(',')
    }
    importMemberRef.value.importFlag = true;
  }

// =============== 导入结束 ========================

  // 时间选择框
const disabledDate = (time)=>{
    return new Date().getTime()-1*24*3600*1000 > time.getTime();
}

  // 时间限定
  const shortcuts = ref([ 
    {
      text: '当前时间',
      value: new Date(),
    },
  ]);


  const {
    pageConfig,
    listData,
    total,
    handleSizeChange,
    handleCurrentChange } = useManualPaging(storeList, { layout: 'prev, pager, next' })
  const selectStoteRef = ref(null)



  const handleOpenStoreDialog = ()=>{
    selectStoteRef.value?.openModal(storeList.value)
  }
  const backStoreValue = (value)=>{
    formRef.value.validate()
  const rangeLength = [...Object.values(activeGoods.value)].flat(Infinity).length
  if(!rangeLength){
    storeList.value = value
    return
  }
  const oldBrands = storeList.value.map(item => item.brandId).filter(item => item)
  const newBrands = value.map(item => item.brandId).filter(item => item)
  

  // 如果没有变化则不做处理
  // const idBrandChange = useDiffStoreValue(storeList.value, value)

  const idBrandChange = useDiffBrandId(oldBrands,newBrands)
  if(!idBrandChange) {
    storeList.value = value
    return
  }


    ElMessageBox.confirm('提交后将清空活动范围，是否继续？', '提示', {
    type: 'error'
    }).then(() => {
      storeList.value = value
      for(let key in activeGoods.value){
        activeGoods.value[key] = []
      }
    })
  }




  const preJudge = (value) => {
    const rangeLength = [...Object.values(activeGoods.value)].flat(Infinity).length
      if(!rangeLength){
        return false
      }
      const oldBrands = storeList.value.map(item => item.brandId).filter(item => item)
      const newBrands = value.map(item => item.brandId).filter(item => item)
      
      const idBrandChange = useDiffBrandId(oldBrands,newBrands)
      if(!idBrandChange) {
        return false
      }else{
        return true
      }
  }
  const delStore = (row, index) => {
    const delstoreList = JSON.parse(JSON.stringify(storeList.value))
    delstoreList.splice(index,1)
    const resultJudge =  preJudge(delstoreList)
    console.log(resultJudge,'resultJudge');
    ElMessageBox(
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
            title: '提示',
            showCancelButton: true,
            confirmButtonClass: 'delete',
            message: !resultJudge ? "确定要删除该门店吗?" : '检测到经营范围发生，提交后将清空活动商品，是否继续？',
            beforeClose: async (action, instance, done) => {
                if (action === 'confirm') {
                    instance.confirmButtonLoading = true
                    instance.confirmButtonText = 'Loading...'
                    try {

                        storeList.value.splice(index, 1)
                        if(resultJudge){
                          for(let key in activeGoods.value){
                            activeGoods.value[key] = []
                          }
                        }
                        ElMessage.success('删除成功');

                        console.log(oldBrandList,storeList.value);

                        // _getStoreLsit(1);
                    } catch (error) {
                        // ElMessage.error('删除失败');
                    }finally{

                        instance.confirmButtonLoading = false
                        done()
                       
                    }
                    
                } else {
                    done()
                }
            },
        }
    )




  }
  
  const selectRangeRef = ref(null)
  const activeGoods = ref({
    '疗程':[],
    '套餐':[],
    '项目':[],
    '产品':[]
  })
  const activeType = ref('疗程')
  const handleOpenRangeDialog = ()=>{
    console.log(storeList.value,'storeList.value');
    const storeIds = storeList.value.map(item => item.brandId).filter(item => item).join(',')
    selectRangeRef.value?.openRange(activeType.value, ...[ ...Object.values(activeGoods.value), storeIds])
  }
  const backRangeValue = (type,...args)=>{
    activeGoods.value['疗程'] = args[0]
    activeGoods.value['套餐'] = args[1]
    activeGoods.value['项目'] = args[2]
    activeGoods.value['产品'] = args[3]
  }

  watch('activeType',() => {
    console.log('变化le');
  })
// 商品分页

const activeGoodsPage = computed(()=>{
  return activeGoods.value[activeType.value]
})

  const {
    pageConfig:goodsPageConfig,
    listData:goodsListData,
    total:goodsTotal,
    handleSizeChange:goodsHandleSizeChange, 
    handleCurrentChange:goodsHandleCurrentChange
 } = useManualPaging(activeGoodsPage, { layout: 'prev, pager, next' })

  const delActiveGoods = (index)=>{
    ElMessageBox.confirm('确定删除该门店吗？', '提示', {
    type: 'error',
    confirmButtonClass: 'el-button--danger',
  }).then(() => {
    activeGoods.value[activeType.value].splice(index,1)
  })


    // activeGoods.value[activeType.value].splice(index,1)
  }

  // 清除商品列表
  const clearGoods = ()=>{
    activeGoods.value = {
      '疗程': [],
      '套餐': [],
      '项目': [],
      '产品': []
    }
  }


  //批量填充
  const bulkFill = () => {
    // 折扣
    if(activeGoods.value[activeType.value].discountAll){
      fillingMode('discount',activeGoods.value[activeType.value].discountAll)
      activeGoods.value[activeType.value].discountAll = ''
    }
    // 折后价
    if(activeGoods.value[activeType.value].discountPriceAll){
      fillingMode('discountPrice',activeGoods.value[activeType.value].discountPriceAll)
      activeGoods.value[activeType.value].discountPriceAll = ''
    }
    // 累计限购
    if(activeGoods.value[activeType.value].cumulatePriceAll){
      fillingMode('cumulatePrice',activeGoods.value[activeType.value].cumulatePriceAll)
      activeGoods.value[activeType.value].cumulatePriceAll = ''
    }
  }

  // 填充方式
  const fillingMode = (key,value) => {
    console.log(key,value,'key&value');
    activeGoods.value[activeType.value].forEach(item => {
        item[key] = value
      })
  }






// 避免首次触发change事件
const Dateflag = ref(false)



  // 活动时间校验规则
  const activeDateRule = [{
    required: true,
    validator: (rule, value, callback) => {
      if(!Dateflag.value){
        Dateflag.value = true
        return
      }
     
      if (!form.value.activeDate || form.value.activeDate.length == 0) {
        callback(new Error('请选择活动时间'))
      }if(form.value.activeDateType == 1 && form.value.activeDate.length < 2){
        callback(new Error('活动开始时间和结束时间必填'))
      }else {
        callback()
      }
    }, 
    trigger: ['blur','change']
  }]

  //门店校验规则
  const storeListRule = [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!storeList.value.length) {
          callback(new Error('请选择门店'))
        } else {
          callback()
        }
      }, trigger: ['blur','change']
    }
  ]
  // 折扣限制
 const discountRules = [{
  required: true,
  validator: (rule, value, callback) => {
    if (!value) {
      callback(new Error('折扣不可为空或0'))
    }else{
      callback()

    }
  },
 }]

//  表格限购校验
const discountValidateTable = (row)=>{
    return [{
      required: true,
      validator: (rule, value, callback) => {
        if(!row.discount){
          callback('折扣不可为空或0')
        }else{
         callback()
        }
      },
      message: '折扣不可为空或0',
      trigger: ['blur','change']
    }]
  }

// 表格折后价校验
const discountPrice = (row) => {
  return [{
      required: true,
      validator: (rule, value, callback) => {
        if(!row.discountPrice){
          callback('折后价格不可为空或0')
        }else{
         callback()
        }
      },
      message: '折后价格不可为空或0',
      trigger: ['blur','change']
    }]
}

// 表格累计限购
const cumulatePriceRules = (row) => {
  return [{
      required: true,
      validator: (rule, value, callback) => {
        if(!row.cumulatePrice){
          callback('累计限购不可为空或0')
        }else{
         callback()
        }
      },
      message: '累计限购不可为空或0',
      trigger: ['blur','change']
    }]
}

 const activeGoodsRule = [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (![...Object.values(activeGoods.value)].flat().length) {
          callback(new Error('请选择活动商品'))
        } else {
          callback()
        }
      }, trigger: 'blur'
    }
  ]
  // 开启时间变化
  const activeDateTypeChange = () => {
    // form.value.activityCycleType = 1
    form.value.activeDate = []
  }
// 时间选项卡(每周每月切换)
  const activityCycleTypeChange = (val) => {
    form.value.activeDate = []
  }
  // 是否开启限购
  const changeRestriction = (val) => {
    console.log(val,'是否开启限购');
    if(val == 1){
      form.value.rangeActive = 1
    }else{
      form.value.rangeActive = 0
    }
  }

  // 活动对象
  const changeActiveObject = (val) => {
    console.log(val,'活动对象');
  }

  // 适用门店变化
  const useStoreChange = (val) => {
    if ([...Object.values(activeGoods.value)].flat().length) {
    ElMessageBox.confirm('提交后将清空活动范围，是否继续？', '提示', {
      type: 'error',
    }).then(() => {
      form.value.useStore = val
      storeList.value = []
      for(let key in activeGoods.value){
        activeGoods.value[key] = []
     }
    }).catch(() => {

    }) 
    } 
    else {
      form.value.useStore = val
    }
  }
  //============保存缓存操作业务start============
  const cancel = () => {
    reset()
    topBar.value.backHandle()
  }

  const reset = ()=>{
  activeStep.value = 0
  pageId.value = null
  form.value = {
    activeName: '',
    activeDateType: 0,
    activeDate: [],
    // useStore: 1,
    isRestriction:0, //是否限购
    activeObject:0, //活动对象
    memberType:false, //会员类型
    membershipLevel:[], //会员等级
    rangeActive:0, //活动范围
    discount:'', //折扣
    availablGoods:'', //可用商品折扣
    activityCycleType:0,
    chooseRadius:true,//百分比或折后
    useStore:0, // 全部门店或指定
  }
  storeList.value = []
  activeGoods.value = {
    '疗程':[],
    '套餐':[],
    '项目':[],
    '产品':[]
  }
  formRef.value.resetFields()
}
  
  // 下一步
  const nextHandle = ()=>{
    if(activeStep.value == 0){
      if(form.value.activeDateType == 1){
          if (!compareTimestampsAndValidate(form.value.activeDate[0], form.value.activeDate[1])) {
              ElMessage.error('结束时间不能小于开始时间且不能小于当前时间');
              return
          } 
      }
        formRef.value.validate((validOne, fields,msg)=>{
          
            if(!validOne){
                if(form.value.useStore == 1){
                    if(storeList.value.length<=0){
                        ElMessage.error('请选择门店！');
                        return;
                    }
                }
                // activeStep.value++;
                // form.value.isRestriction == 1 ? form.value.rangeActive = 1 : form.value.rangeActive = 2
            }else{
              
              activeStep.value++;
            }
        })
    }

    
    if(activeStep.value >= 1){

      formRef.value.validate(async (valid) => {
    if(!valid) return
    if (activeStep.value !== stepBarList.length - 1) {
      activeStep.value++
      return
    }
    formRef1.value.validate(async (valid1,object) => {
      if (valid && valid1) {
        try{
          loading.value = true
          // const params = {
          //   ...form.value,
          //   storeList: storeList.value,
          //   activeGoods: activeGoods.value,
          // }
          for(let key in activeGoods.value){
            if(form.value.rangeActive == 1 && form.value.chooseRadius){
              console.log('1');
              const isNoInput = activeGoods.value[key].some(item => !item.discount)
              console.log(isNoInput,'isNoInput');
                if(isNoInput){
                  ElMessage.error(`检测到${key}有未填写,请完善`)
                  activeType.value = key
                  return
                }
            }else if(form.value.rangeActive == 1 && !form.value.isRestriction){
              console.log('2');
              const isNoInput1 = activeGoods.value[key].some(item => !item.discountPrice)
              if(isNoInput1){
                ElMessage.error(`检测到${key}有未填写,请完善`)
                activeType.value = key
                return
              }
            }
           
            if(form.value.isRestriction == 1){
              console.log('3');
              const isNoInput2 = activeGoods.value[key].some(item => !item.cumulatePrice)
              if(isNoInput2){
                ElMessage.error(`检测到${key}有未填写,请完善`)
                activeType.value = key
                return
              }
            }

            

           
        }
          const params = {
            // 活动类型 2: 折扣限购;3: 新人特惠
            activityId:'',
            activityType:2,
            activityName:form.value.activeName,
            activityTimeType:form.value.activeDateType,
            timeCycleType:form.value.activityCycleType,
            // timeCycleList:form.value.activeDate,
            isLimited:form.value.isRestriction,
            limitedCount:1,
            activityMember:form.value.activeObject,
            // activityMemberType:form.activeObject ? ,
            businessScope:form.value.useStore,
            businessScopeData:storeList.value.map(item=>{
              return {
                storeId:item.id,
                storeFunctionType:[item.isShop?2:0,item.isHall?1:0].filter(Boolean),
              }
            }),
            activityRule:form.value.rangeActive,
            activityRuleList: Object.keys(activeGoods.value).map(item=>{
              return {
                activityType:activityTypeEnum[item],
                discountsType:form.value.chooseRadius ? 1 : 0,
                ruleData:activeGoods.value[item].map(goods=>{
                  return {
                    productId:goods.id,
                    discountedPrices: form.value.rangeActive == 1 ? form.value.chooseRadius ? goods.discount : goods.discountPrice : null,
                    limitCount:form.value.isRestriction ? goods.cumulatePrice : null
                  }
                })
              }
            }).filter(item=>item.ruleData.length),
          }
          if(form.value.activeDateType){
            params.activityStartTime = form.value.activeDate[0]
            params.activityEndTime = form.value.activeDate[1]
          }else{
            // console.log(form.value.activeDate,'cycleList.value');
              params.timeCycleList = form.value.activeDate.map(item =>cycleList.value.findIndex(i=>i.label == item) + 1)
              console.log(params.timeCycleList,'params.timeCycleList');
          }

          if(form.value.activeObject == 0){
              // 全部会员
              params.activityMemberType = form.value.memberType ? 1 : 0
          }else{
            // 指定会员
            params.activityMemberTypeList = form.value.membershipLevel
          }

          // 可用商品折扣或者不可用商品折扣
        switch (form.value.rangeActive) {
          case 0:
              params.discounts = form.value.discount
            break;
          // case 1:
          //   params.discounts = ''
          //   break;
          case 2:
            params.discounts = form.value.availablGoods
            break;  
          default:
            break;
        }
          if (!isCopy.value && isEdit.value) {
            params.activityId = pageId.value
          }
          await newUserActivityOperate(params)
          ElMessage.success(`${isCopy.value?'复制': isEdit.value? '修改' : '新增'}成功`)
          useTableRefresh(searchTableRef,isEdit.value)
          cancel()

          // console.log('params', params)
          // return
          if (!isCopy.value && isEdit.value) {
            params.activityId = pageId.value
          }
        }finally{
          loading.value = false
        }
      }else{
        elementPosition()
      }
    })
  })


    }
}


// 上一步
const prevHandle = ()=>{
    activeStep.value --;
}
  // ============保存缓存操作业务start============

  </script>
  
  <style lang="less" scoped>
  div {
    box-sizing: border-box;
  }
  
  .page-main {
    padding: 16px 24px;
  }
  
  .stepBar-box {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    border-radius: 4px;
    overflow: hidden;
  
    .stepBar-item {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: -16px;
      width: 306px;
      height: 40px;
      color: #000;
      font-size: 16px;
      -webkit-clip-path: polygon(100% 0, 100% 50%, 100% 100%, 0% 100%, 5% 50%, 0% 0%);
      clip-path: polygon(100% 0, 100% 50%, 100% 100%, 0% 100%, 5% 50%, 0% 0%);
      background: #EBF2FF;
      cursor: pointer;
    }
  
    .stepBar-activeItem {
      color: #fff;
      background: #3480FF;
    }
  
    .stepBar-item:first-of-type {
      margin-left: 0;
      -webkit-clip-path: polygon(0% 0%, 95% 0, 100% 50%, 95% 100%, 0% 100%);
      clip-path: polygon(0% 0%, 95% 0, 100% 50%, 95% 100%, 0% 100%);
    }
  }
  
  :deep(.el-form) {
    .el-form-item__label {
      color: #222;
    }
  
    .el-radio {
      color: #000;
    }
    .el-form-item{
      margin-bottom: 8px;
    }
 

    .el-table .cell{

    
      padding: 16px  16px 10px 16px;
      .el-input{
        width:120px;
        // min-height: 30px;
      }
      .el-form-item__label{
        padding: 0 1px 0 0;
        line-height: 36px;
      }
    }

    .el-table{
      .el-table__cell{
        padding: 0;  
      }
    }
    .button-tips{
      margin-left: 8px;
      color: #666666;
      font-family: "PingFang SC";
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
      line-height: 12px;
    }
   
  }
  
  .myPagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }
  :deep(.el-radio-button:first-child .el-radio-button__inner) {
    border-left: 1px solid #3480FF;
  }

  :deep(.el-switch__core ){
    background: #3480FF;
  }
  :deep( .el-switch__label){
    color: #000;
   
  }
  :deep(.el-switch__label.is-active){
      color: #3480FF !important;
    }

    .member-tips{
      margin-left: 122px;
      margin-bottom: 8px;
      color: #666666;
      font-family: "PingFang SC";
      font-size: 12px;
      font-style: normal; 
      font-weight: 400;
      line-height: 12px;
    }

    .choose-view{
      padding-left: 72px;
      width:100%;
      margin: 16px 0 16px 7px;
      .choose-button{
        margin-bottom: 16px;
        display: flex;
        align-items: center;
      }
      .active-type{
        margin-bottom: 8px; 
        display: flex; 
        justify-content: space-between;
      }
      .page-bar{
        display: flex;
        flex-direction: row-reverse;
        padding-top: 8px;
        box-sizing: border-box;
      }
    }

  
  </style>

 <style lang="less">
  .myDatePicker{
    .el-picker-panel__body-wrapper {
    min-height: 376px !important;
    }
    .el-date-range-picker__time-header{
      position: absolute;
      border-bottom: 0 solid var(--el-datepicker-inner-border-color);
      font-size: 12px;
      padding: 8px 5px 5px 5px;
      display: table;
      width: 100%;
      box-sizing: border-box;
      left: 0 !important;
      bottom: 8px !important;
    }
  }
 
 
   
</style>
